//
//  DictionariesController.m
//  Words2
//
//  Created by Mathieu on 22/08/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//
// Class inherits from NSObjectController and controls dictionary objects including the creation
// Might make it specialised to a particular kind of dictionary though.
#import "DictionariesController.h"
#import "DictProtocolDictionary.h"
#import "StardictDict.h"



@implementation DictionariesController

-(IBAction)openDictionaryDownloaderView:(id)sender{
	[mainWindowTabView selectTabViewItemWithIdentifier:@"DictionaryDownloader"];
}

#pragma mark Dictionary Creation / Deletion

// interface action which gathers the needed data and creates a new dictionary object.
- (IBAction)createNewDictionary:(id)sender{
	//create a new dict protocol dictionary (because that's the tab view that is selected)
	NSManagedObject *newDict = [NSEntityDescription insertNewObjectForEntityForName:@"DictProtocolDict" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
	// set the name, server, database etc
	[newDict setValue:[dictionaryName stringValue] forKey:@"name"];
	[newDict setValue:[server stringValue] forKey:@"serverName"];
	[newDict setValue:[database stringValue] forKey:@"databaseName"];
	[newDict setValue:[username stringValue] forKey:@"username"];
	[newDict setValue:[password stringValue] forKey:@"password"];
	[newDict setValue:[targetLanguages stringValue] forKey:@"targetLanguages"];
	[newDict setValue:[capabilities stringValue] forKey:@"capabilities"];
	[customDictPanel close];
}

-(IBAction)removeSelectedDictionaryFromMOC:(id)sender{
	//panel to confirm deletion
	DictionaryMO *dictToDelete = [[availableDictionaries selectedObjects] objectAtIndex:0];
	[[[NSApp delegate] managedObjectContext] deleteObject:dictToDelete];


}


#pragma mark Bindings Compatability
// fetches from the moc all the dictionaries that are currently available for the selected language.
- (NSSet*)availableDictionaries{
	return [NSSet setWithObjects:@"nothing", nil]; //some set of dictioanries from a fetch request with an appropriate predicate set.
}


- (NSArray *)supportedDictionaryTypes{
	return [NSArray arrayWithObjects:@"dict Protocol Dictionary", @"XML", nil];
}

#pragma mark Import / Export Dictionaries
//method which creates a bundle from the selected dictionary, archives it, and saves it as a wordsdict to a specified location.



- (IBAction)exportDictionary:(id)sender{
	int runResult;
	DictionaryMO *dict = [[availableDictionaries selectedObjects] objectAtIndex:0];
	NSData *data;
	NSSavePanel *panel = [NSSavePanel savePanel];
	[panel setRequiredFileType:@"wordsdict"];
	runResult = [panel runModalForDirectory:NSHomeDirectory() file:nil];
	
	/* if successful, save file under designated name */
	if (runResult == NSOKButton) {
		data = [NSKeyedArchiver archivedDataWithRootObject:dict];
		if (![data writeToFile:[panel filename] atomically:YES])
			NSLog(@"Could Note Write to File");
	}
	

}
- (IBAction)importDictionary:(id)sender{
	int runResult;
	DictionaryMO *aDictionary;
	NSOpenPanel *panel = [NSOpenPanel openPanel]; //get the open panel
	[panel setAllowedFileTypes:[NSArray arrayWithObject:@"wordsdict"]];
	[panel setAllowsMultipleSelection:YES];
	runResult = [panel runModalForDirectory:NSHomeDirectory() file:@""];
	if(runResult == NSOKButton){
		NSArray *filesToOpen = [panel filenames];
		int i, count = [filesToOpen count];
        for (i=0; i<count; i++) {
            NSString *aFile = [filesToOpen objectAtIndex:i];
			aDictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:aFile];
			// do something with the dictionary, like asking the user if they want to use it right away.
        }
	}		
}


-(void)didEnd:(NSSavePanel *)sheet
   returnCode:(int)code
  contextInfo:(void *)contextInfo{
	DictionaryMO *dict = [[availableDictionaries selectedObjects] objectAtIndex:0];
	NSData *data;
	if(code == NSOKButton){
		data = [NSKeyedArchiver archivedDataWithRootObject:dict];;
		[data writeToFile:[sheet filename] atomically:YES];
	}
}


#pragma mark Convenience Methods
// Method which adds a dictionary to a language so that it is set to be used in defining words.
- (void)addDictionary:(DictionaryMO *)dictionary forUseInLanguage:(LanguageMO *)language{
	[language addObject:dictionary toToManyRelationshipForKey:@"dictionaries"];
}

@end
